/*
 * @(#)QueueAppender.java
 * 2011-5-29 下午10:12:24
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.common.log;

import java.util.concurrent.BlockingQueue;

import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import com.qyxx.platform.common.queue.QueuesHolder;

/**
 *  轻量级的Log4j异步Appender.
 * 
 *  将所有消息放入QueueManager所管理的Blocking Queue中.
 * 
 *  @see QueuesHolder
 *  
 *  @author gxj
 *  @version 1.0
 *  @since 1.6 2011-5-29 下午10:12:24
 */
public class QueueAppender extends org.apache.log4j.AppenderSkeleton {

	protected String queueName;

	protected BlockingQueue<LoggingEvent> queue;

	/**
	 * AppenderSkeleton回调函数, 事件到达时将时间放入Queue.
	 */
	@Override
	public void append(LoggingEvent event) {
		if (queue == null) {
			queue = QueuesHolder.getQueue(queueName);
		}

		boolean sucess = queue.offer(event);

		if (sucess) {
			LogLog.debug("put event to queue success:" + new LoggingEventWrapper(event).convertToString());
		} else {
			LogLog.error("Put event to queue fail:" + new LoggingEventWrapper(event).convertToString());
		}
	}

	/**
	 * AppenderSkeleton回调函数,关闭Logger时的清理动作.
	 */
	public void close() {
	}

	/**
	 * AppenderSkeleton回调函数, 设置是否需要定义Layout.
	 */
	public boolean requiresLayout() {
		return false;
	}

	/**
	 * Log4j根据getter/setter从log4j.properties中注入同名参数.
	 */
	public String getQueueName() {
		return queueName;
	}

	/**
	 * @see #getQueueName()
	 */
	public void setQueueName(String queueName) {
		this.queueName = queueName;
	}
}
